package com.tanhua.server.service.impl;

import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Sound;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.SoundVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.PeachblossomService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

/**
 * @author wjs
 * @version 1.0
 * @date 2022/1/8 0008 下午 2:36
 */
@Service
public class PeachblossomServiceImpl implements PeachblossomService {

    @DubboReference
    private SoundApi soundApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Override
    public void saveSound(MultipartFile soundFile) throws IOException {
        if (soundFile.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }

        String soundUrl = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());

        Sound sound = new Sound();
        sound.setUserId(UserHolder.getUserId());
        sound.setSoundUrl(soundUrl);

        String soundId = soundApi.saveSound(sound);
        if (soundId.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }
    }

    @Override
    public SoundVo findOneByRandom() {
        String key = Constants.PEACHBLOSSOM_KEY + UserHolder.getUserId();
        Integer remainingTimes = (Integer) redisTemplate.opsForValue().get(key);
        if (remainingTimes != null && remainingTimes < 0) {
            throw new BusinessException(ErrorResult.peachblossomError());
        }

        Sound sound = soundApi.findOneByRandom(UserHolder.getUserId());
        Long userId = sound.getUserId();
        UserInfo userInfo = userInfoApi.findById(userId);
        SoundVo vo = SoundVo.init(userInfo, sound);

        Long secondsNextEarlyMorning = getSecondsNextEarlyMorning();
        if (remainingTimes == null) {
            redisTemplate.opsForValue().set(key, 9, Duration.ofSeconds(secondsNextEarlyMorning));
            vo.setRemainingTimes(9);
        } else {
            redisTemplate.opsForValue().set(key, remainingTimes - 1, Duration.ofSeconds(secondsNextEarlyMorning));
            vo.setRemainingTimes(remainingTimes - 1);
        }
        soundApi.remove(sound);
        return vo;
    }

    /**
     * 判断当前时间距离第二天凌晨的秒数
     *
     * @return 返回值单位为[s:秒]
     */
    public Long getSecondsNextEarlyMorning() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }
}
